package com.lenovo.testreport.test.server.api.service;

import com.lenovo.testreport.general.service.GeneralCaseService;
import com.lenovo.testreport.test.server.api.mapper.TestServiceApiCaseMapper;
import com.lenovo.testreport.test.server.api.model.TestServiceApiCaseWithBLOBs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CaseServiceImpl implements GeneralCaseService {
    @Autowired
    TestServiceApiCaseMapper mapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public List<TestServiceApiCaseWithBLOBs> findByRid(String tablename, int rid) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/rid/" + rid;
        redisTemplate.setKeySerializer(redisSerializer);
        List<TestServiceApiCaseWithBLOBs> List = (List<TestServiceApiCaseWithBLOBs>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectByRid(tablename, rid);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
        }
        return List;
    }

    @Override
    public List<TestServiceApiCaseWithBLOBs> findByCid(String tablename, int cid) {

        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/cid/" + cid;
        redisTemplate.setKeySerializer(redisSerializer);
        List<TestServiceApiCaseWithBLOBs> List = (List<TestServiceApiCaseWithBLOBs>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectByCid(tablename, cid);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
        }
        return List;
    }

    @Override
    public int modifycase(String tablename, Object case1) {
        TestServiceApiCaseWithBLOBs case2 = (TestServiceApiCaseWithBLOBs) case1;
        int result = mapper.updateTrackByCid(tablename, case2);
        String key = tablename + "/cid/" + case2.getCid();
        redisTemplate.delete(key);
        return result;
    }
}
